<?php
/**
 *  用户服务层
*/

namespace app\api\service;

use app\api\service\Users as ServiceUsers;
use app\facade\Basic;
use app\api\model\Customer;
use app\common\RedisClient;
use think\facade\Cache;
use think\facade\Config;

class Login
{
    /**
     *  用户登录
    */

    public function login($param)
    {
        $where = [];
        /* 判断邮箱 */
        if(filter_var($param['account'],FILTER_VALIDATE_EMAIL)){
            $where['email'] =  $param['account'];
        } else {
            /* 判断手机号 */
            if (preg_match("/^1[34578]{1}\d{9}$/",$param['account'])) {
                $where['phone'] = $param['account'];
            } else {
                // 用户名登录
                $where['cusname'] = $param['account'];
            }
        }

        $result = Customer::where($where)->find();


        if(!$result){
            return Basic::data(1,'login.userDoesNotExist');
        }

        /* 密码验证 */
        $password_salt = Config::get('api.password_salt');
        $password = md5(md5($param['password'].$password_salt.$result->create_time));

        if($result->password !== $password) {
            return Basic::data(1,'login.verificationPasswordError');
        }

        /* 验证是否被禁用 */
        if( $result->login_status == 2 ) {
            return Basic::data(1,'login.userIsDisabled');
        }

        /* 保存登录信息 */
        $token = new Token();
        $token = $token->get($result);

        /* 更新登陆信息 */
        $result->login_num = ($result->login_num + 1);
        $result->last_login_time = date("Y-m-d H:i:s",time());
        $result->last_ip = $param['ip'];
        $result->is_login = 1;
        $result->save();

        $redis = new RedisClient();
        $redis->set('customer_token:'.$result->id, $token);

        $serviceRetrieve = new ServiceUsers();
        $userinfo = $serviceRetrieve->userinfo($result);

        $logininfo =[
            'token' => $token,
            'expire_in' => config('api.token_expire_in'),
            'role' => $result->role,
            'userinfo' => $userinfo
        ];

        return Basic::data(0,'login.loginSuccessful',$logininfo);
    }

    /**
     *  退出登录
    */
    public static function logout($param)
    {

        $result = Customer::where('id',$param['user_id'])->find();

        if (empty($result)) {
            return Basic::data(1,'login.userDoesNotExist');
        }

        $result->is_login = 2;

        if ($result->save()) {
            Cache::delete($param['token']);
            return Basic::data(0,'login.exitSuccessful');
        } else {
            return Basic::data(1,'login.exitFailed');
        }
    }

}
